﻿
using NPoco;
using System.Collections.Generic;
using System.Linq;
using YYBlog.Core.Entity;
using NPoco.Linq;
namespace YYBlog.Core.ViewProjections.Home
{
    public class TaggedBlogPostsViewModel
    {
        public IEnumerable<BlogPost> Posts { get; set; }

        public string Tag { get; set; }
    }

    public class TaggedBlogPostsBindingModel
    {
        public string Tag { get; set; }
    }

    public class TaggedBlogPostsViewProjection : IViewProjection<TaggedBlogPostsBindingModel, TaggedBlogPostsViewModel>
    {
        private readonly Database _db;

        public TaggedBlogPostsViewProjection(Database db)
        {
            _db = db;
        }

        public TaggedBlogPostsViewModel Project(TaggedBlogPostsBindingModel input)
        {
            //var posts = (from p in _db.Select<BlogPost>("from " + DBTableNames.BlogPosts)
            //             where p.IsPublished && p.Tags.Contains(input.Tag)
            //             orderby p.PubDate descending
            //             select p)
            //         .ToList();
            var posts = _db.Query<BlogPost>().OrderByDescending(p => p.PubDate).Where(p => p.IsPublished && p.Tags.Contains(input.Tag)).ToList();
            if (!posts.Any())
                return null;
            //var tagName = _db.SelectKey<Tag>(DBTableNames.Tags, posts.First().Tags[0]).Name;
            //var tagName=input.Tag
            return new TaggedBlogPostsViewModel
            {
                Posts = posts,
                Tag = input.Tag
            };
        }
    }
}